package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.TTemplate;
import com.ruoyi.system.domain.bo.SheetBo;
import com.ruoyi.system.domain.vo.TTemplateVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.TReportBo;
import com.ruoyi.system.domain.vo.TReportVo;
import com.ruoyi.system.domain.TReport;
import com.ruoyi.system.mapper.TReportMapper;
import com.ruoyi.system.service.ITReportService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

import static com.ruoyi.common.helper.LoginHelper.getLoginUser;

/**
 * 上报Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-06
 */
@RequiredArgsConstructor
@Service
public class TReportServiceImpl implements ITReportService {

    private static final String defaultJson = "[{\"name\":\"Sheet1\",\"color\":\"\",\"status\":\"1\",\"order\":\"0\",\"config\":{},\"index\":0,\"jfgird_select_save\":[],\"luckysheet_select_save\":[{\"row\":[0,0],\"column\":[0,0],\"row_focus\":0,\"column_focus\":0,\"left\":0,\"width\":73,\"top\":0,\"height\":19,\"left_move\":0,\"width_move\":73,\"top_move\":0,\"height_move\":19}],\"visibledatarow\":[20,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340,360,380,400,420,440,460,480,500,520,540,560,580,600,620,640,660,680,700,720,740,760,780,800,820,840,860,880,900,920,940,960,980,1000,1020,1040,1060,1080,1100,1120,1140,1160,1180,1200,1220,1240,1260,1280,1300,1320,1340,1360,1380,1400,1420,1440,1460,1480,1500,1520,1540,1560,1580,1600,1620,1640,1660,1680],\"visibledatacolumn\":[74,148,222,296,370,444,518,592,666,740,814,888,962,1036,1110,1184,1258,1332,1406,1480,1554,1628,1702,1776,1850,1924,1998,2072,2146,2220,2294,2368,2442,2516,2590,2664,2738,2812,2886,2960,3034,3108,3182,3256,3330,3404,3478,3552,3626,3700,3774,3848,3922,3996,4070,4144,4218,4292,4366,4440],\"ch_width\":4560,\"rh_height\":1760,\"luckysheet_selection_range\":[],\"zoomRatio\":1,\"celldata\":[]},{\"name\":\"Sheet2\",\"color\":\"\",\"status\":\"0\",\"order\":\"1\",\"config\":{},\"index\":1,\"celldata\":[]},{\"name\":\"Sheet3\",\"color\":\"\",\"status\":\"0\",\"order\":\"2\",\"config\":{},\"index\":2,\"celldata\":[]}]";
    private final TReportMapper baseMapper;

    /**
     * 查询上报
     */
    @Override
    public TReportVo queryById(String pkid){
        TReportVo vo = new TReportVo();
        LambdaQueryWrapper<TReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TReport::getPkid,pkid);
        List<TReportVo> vos = baseMapper.selectVoList(wrapper);
        if (vos.isEmpty()) {
            vo.setReportData(JSONUtil.parseArray(defaultJson));
        }else{
            vo=vos.get(0);
            vo.setReportData(JSONUtil.parseArray(vos.get(0).getReportData()));
        }

        return vo;
    }

    /**
     * 查询上报列表
     */
    @Override
    public TableDataInfo<TReportVo> queryPageList(TReportBo bo, PageQuery pageQuery) {
        LoginUser user = getLoginUser();
        assert user != null;
        if (user.getRoles().get(0).getRoleName().equals("车间上报员")){
            bo.setReportName(user.getUsername());
        }
        LambdaQueryWrapper<TReport> lqw = buildQueryWrapper(bo);
        Page<TReportVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询上报列表
     */
    @Override
    public List<TReportVo> queryList(TReportBo bo) {
        LambdaQueryWrapper<TReport> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TReport> buildQueryWrapper(TReportBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TReport> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getReportName()), TReport::getReportName, bo.getReportName());
        lqw.eq(bo.getReportTime() != null, TReport::getReportTime, bo.getReportTime());
        lqw.eq(StringUtils.isNotBlank(bo.getPlantId()), TReport::getPlantId, bo.getPlantId());
        lqw.eq(StringUtils.isNotBlank(bo.getReportId()), TReport::getReportId, bo.getReportId());
        lqw.eq(StringUtils.isNotBlank(bo.getAudit()), TReport::getAudit, bo.getAudit());
        return lqw;
    }

    /**
     * 新增上报
     */
    @Override
    public Boolean insertByBo(TReportBo bo) {
        TReport add = BeanUtil.toBean(bo, TReport.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPkid(add.getPkid());
        }
        return flag;
    }

    /**
     * 修改上报
     */
    @Override
    public Boolean updateByBo(TReportBo bo) {
        TReport update = BeanUtil.toBean(bo, TReport.class);
        if (ObjectUtil.isNull(bo.getReportData())){
            update.setReportData(defaultJson);
        }
        update.setReportData(JSONUtil.toJsonStr(update.getReportData()));
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TReport entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除上报
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
    @Override
    public int saveLuckySheet(SheetBo bo) {
        LambdaUpdateWrapper<TReport> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TReport::getReportData,bo.getData())
                .eq(TReport::getPkid,bo.getPkid());
        return baseMapper.update(wrapper);
    }
}
